﻿/******************************************************/
// HomePage プレゼンテーションクラス  
/******************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using MAA.Business;
using MAA.Entity;
using System.Drawing;

namespace MAA.Presentation
{
    public partial class HomePage : System.Web.UI.Page
    {
        private ResourceManager rm = new ResourceManager("MAA.Presentation.language", 
            System.Reflection.Assembly.GetExecutingAssembly());
        private CultureInfo m_JapanCulture = new CultureInfo("ja-JP");
        private CultureInfo m_VietnameCulture = new CultureInfo("vi");

        private void UpdateUI()
        {
            langMaxPrice.Text = rm.GetString("langMaxPrice");
            langMinPrice.Text = rm.GetString("langMinPrice");
            langNewest.Text = rm.GetString("langNewest");
            langPriceMarket.Text = rm.GetString("langPriceMarket");
            langPostTableHomePage.Text = rm.GetString("langPostTableHomePage");
            langProvince.Text = rm.GetString("langProvince");
            langRiceType.Text = rm.GetString("langRiceType");
            CompareValidator1.Text = rm.GetString("langMinPriceHigher0");
            CompareValidator3.Text = rm.GetString("langMaxPriceHigher0");
            CompareValidator4.Text = rm.GetString("langMaxPriceHigherMinPrice");
            rbtPrice.Text = rm.GetString("langPrice");
            rbtTime.Text = rm.GetString("langTime");
            dgvPosts.Columns[2].HeaderText = rm.GetString("langRiceType");
            dgvPosts.Columns[3].HeaderText = rm.GetString("langAmount");
            dgvPosts.Columns[4].HeaderText = rm.GetString("langPriceSell");
            dgvPosts.Columns[5].HeaderText = rm.GetString("langProvince");
            dgvPosts.Columns[6].HeaderText = rm.GetString("langDateBuy");
            dgvRicePrice.Columns[0].HeaderText = rm.GetString("langRiceType");
            dgvRicePrice.Columns[1].HeaderText = rm.GetString("langPriceUpdate");
            dgvRicePrice.Columns[2].HeaderText = rm.GetString("langChange");
            dgvRicePrice.Columns[5].HeaderText = rm.GetString("langDateUpdate");
            imgBtnSearch.ToolTip = rm.GetString("langImgSearchTooltip");
            imgBtnFirst.ToolTip = rm.GetString("langFirst");
            imgBtnPrevious.ToolTip = rm.GetString("langPrevious");
            imgBtnNext.ToolTip = rm.GetString("langNext");
            imgBtnLast.ToolTip = rm.GetString("langLast");
            langlblSource.Text = rm.GetString("langSource");
        }

        /// <summary>
        /// ページロード 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["PresentPage"] = "HomePage";

            /// UI 言語アップデート
            if (Session["language"] == null)
            {
                Session["language"] = "vi";
            }
            if (Session["language"].Equals("vi"))
            {
                Thread.CurrentThread.CurrentUICulture = m_VietnameCulture;
                UpdateUI();
            }
            if (Session["language"].Equals("jp"))
            {
                Thread.CurrentThread.CurrentUICulture = m_JapanCulture;
                UpdateUI();
            }
            if (IsPostBack) return;

            /// urlリンクが活性アカウントの確認リンクのチェック
            string email = Request.QueryString["email"];
            if (!string.IsNullOrWhiteSpace(email))
            {
                // 活性アカウントします
                BOLAccount bolAcc = new BOLAccount();
                string message = "";
                bolAcc.activeAccount(email, out message);
                ClientScript.RegisterStartupScript(this.GetType(), "popup",
                    "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(message) + "');window.location='../HomePage.aspx'</script>");
            }

            /// DropDownListのライス種類のすべての米の種類のビュー名
            BOLNews bolNews = new BOLNews();
            DataTable tblRiceType = new DataTable();
            string messageRiceType = "";
            string lang = Session["language"].ToString();
            if (!bolNews.viewRiceType(lang, out tblRiceType, out messageRiceType))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageRiceType) + "')</script>", false);
            }
            ddlRiceType.DataSource = tblRiceType;
            ddlRiceType.DataValueField = "ID";
            ddlRiceType.DataTextField = "TypeName";
            ddlRiceType.DataBind();
            if (Session["language"].Equals("vi"))
            {
                ddlRiceType.Items.Insert(0, new ListItem(rm.GetString("langAll"), "0"));
            }
            if (Session["language"].Equals("jp"))
            {
                ddlRiceType.Items.Insert(0, new ListItem(rm.GetString("langAll"), "0"));
            }
            ddlRiceType.SelectedValue = "0";

            /// DropDownListの省のすべての州のビュー名
            DataTable tblProvince = new DataTable();
            string messageProvince = "";

            if (!bolNews.viewProvince(lang, out tblProvince, out messageProvince))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageProvince) + "')</script>", false);
            }
            ddlProvince.DataSource = tblProvince;
            ddlProvince.DataValueField = "ID";
            ddlProvince.DataTextField = "Name";
            ddlProvince.DataBind();
            if (Session["language"].Equals("vi"))
            {
                ddlProvince.Items.Insert(0, new ListItem(rm.GetString("langAll"), "0"));
            }
            if (Session["language"].Equals("jp"))
            {
                ddlProvince.Items.Insert(0, new ListItem(rm.GetString("langAll"), "0"));
            }
            ddlProvince.SelectedValue = "0";

            /// すべての取引の記事を見る
            imgBtnSearch_Click(sender, e);

            /// すべてのお米の種類の市場価格ビュー
            lblSource.Text = Common.RICE_SOURCE;
            DataTable tblRicePrice = new DataTable();
            string messageRicePrice = "";
            if (!bolNews.viewRicePrice(lang, out tblRicePrice, out messageRicePrice))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageRicePrice) + "')</script>", false);
            }
            dgvRicePrice.DataSource = tblRicePrice;
            dgvRicePrice.DataBind();

            /// 最新のマーケットニュースのビュー情報
            DataTable tblNews = new DataTable();
            string messageNews = "";
            if (!bolNews.viewNewsUpdate(lang, out tblNews, out messageNews))
            {
                tblNewsInfo.DataSource = null;
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageNews) + "')</script>", false);
            }
            else
            {
                DataView newsDataView = new DataView(tblNews);
                PagedDataSource newsItems = new PagedDataSource();
                newsItems.DataSource = newsDataView;
                tblNewsInfo.DataSource = newsItems;
            }
            tblNewsInfo.DataBind();
        }

        /// <summary>
        /// Button Searchクリック
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnSearch_Click(object sender, EventArgs e)
        {
            /// 検索条件を取得
            /// 基本的な検索条件を取得
            int riceID = Convert.ToInt32(ddlRiceType.SelectedItem.Value);
            short provinceID = Convert.ToInt16(ddlProvince.SelectedItem.Value);
            int priceMin = 0;
            if (!tbxMinPrice.Text.Equals("")) priceMin = Convert.ToInt32(tbxMinPrice.Text.Trim());
            int priceMax = 0;
            if (!tbxMaxPrice.Text.Equals("")) priceMax = Convert.ToInt32(tbxMaxPrice.Text.Trim());

            Session["pageIndex"] = 1;
            Session["riceID"] = riceID;
            Session["provinceID"] = provinceID;
            Session["priceMin"] = priceMin;
            Session["priceMax"] = priceMax;

            Search(riceID, provinceID, priceMin, priceMax);
        }

        /// <summary>
        /// 検索の投稿
        /// </summary>
        /// <param name="riceID"></param>
        /// <param name="provinceID"></param>
        /// <param name="priceMin"></param>
        /// <param name="priceMax"></param>
        private void Search(int riceID, short provinceID, int priceMin, int priceMax)
        {
            BOLTrading bolTrading = new BOLTrading();
            DataTable tblPost = new DataTable();
            string messagePost = "";
            long rowNum = 0;

            /// 高度な検索条件を取得
            int pageSize = dgvPosts.PageSize;
            int pageIndex = Convert.ToInt32(Session["pageIndex"]);
            string sortType = "";
            if (rbtTime.Checked == true)
            {
                sortType = "Time";
            }
            else
            {
                sortType = "Price";
            }

            /// 検索の投稿を行う
            lblPostsMess.Text = null;
            string lang = Session["language"].ToString();
            if (!bolTrading.searchPost(lang, sortType, pageIndex, pageSize, riceID, provinceID, priceMin, priceMax, out tblPost, out rowNum, out messagePost))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messagePost) + "')</script>", false);
            }
            else
            {
                /// searchPost()をチェックします: If searchPost 成功 
                if (tblPost.Rows.Count > 0)
                {
                    // If tblPost にデータがある場合
                    if (rowNum > dgvPosts.PageSize)
                    {
                        // rowNumとpageIndexパラメータによるdgvPostsのページ数の設定
                        Pager(rowNum, pageIndex);
                        enablePaging(true);
                    }
                    else enablePaging(false);
                }
                else
                {
                    enablePaging(false);
                    lblPostsMess.Text = PRLCommon.ChangeLanguageMessage(Common.MESSAGE_NO_DATA_POST_SEARCH);
                }
            }

            /// dgvPostsへtblPostのデータを埋める
            dgvPosts.DataSource = tblPost;
            dgvPosts.DataBind();
        }

        /// <summary>
        /// rowNumとpageIndexパラメータによるdgvPostsのページ数の設定
        /// </summary>
        /// <param name="recordCount"></param>
        /// <param name="currentPage"></param>
        private void Pager(long recordCount, int currentPage)
        {
            lblCurrentPage.Text = currentPage.ToString();
            double dblPageCount = (double)((decimal)recordCount / decimal.Parse(dgvPosts.PageSize.ToString()));
            int pageCount = (int)Math.Ceiling(dblPageCount);
            lblTotalPage.Text = pageCount.ToString();
        }

        /// <summary>
        /// Processing when user changes page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Changed(object sender, EventArgs e)
        {
            int pageIndex = int.Parse(Session["pageIndex"].ToString());
            int pageCount = Convert.ToInt32(lblTotalPage.Text);

            if ((sender as ImageButton).CommandArgument == "First")
            {
                if (pageIndex == 1) return;
                pageIndex = 1;
            }

            if ((sender as ImageButton).CommandArgument == "Previous")
            {
                pageIndex = pageIndex - 1;
                if (pageIndex < 1) return;
            }

            if ((sender as ImageButton).CommandArgument == "Next")
            {
                pageIndex = pageIndex + 1;
                if (pageIndex > pageCount) return;
            }

            if ((sender as ImageButton).CommandArgument == "Last")
            {
                if (pageIndex == pageCount) return;
                pageIndex = pageCount;
            }
            Session["pageIndex"] = pageIndex;

            int riceID = Convert.ToInt32(Session["riceID"]);
            short provinceID = Convert.ToInt16(Session["provinceID"]);
            int priceMin = Convert.ToInt32(Session["priceMin"]);
            int priceMax = Convert.ToInt32(Session["priceMax"]);

            Search(riceID, provinceID, priceMin, priceMax);
        }

        /// <summary>
        /// RadioButton Priceクリックします
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rbtPrice_CheckedChanged(object sender, EventArgs e)
        {
            // Get search condition
            // Get basic search condition
            int riceID = Convert.ToInt32(Session["riceID"]);
            short provinceID = Convert.ToInt16(Session["provinceID"]);
            int priceMin = Convert.ToInt32(Session["priceMin"]);
            int priceMax = Convert.ToInt32(Session["priceMax"]);

            Session["pageIndex"] = 1;

            Search(riceID, provinceID, priceMin, priceMax);
        }

        /// <summary>
        /// RadioButton Timeクリック
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rbtTime_CheckedChanged(object sender, EventArgs e)
        {
            // Get search condition
            // Get basic search condition
            int riceID = Convert.ToInt32(Session["riceID"]);
            short provinceID = Convert.ToInt16(Session["provinceID"]);
            int priceMin = Convert.ToInt32(Session["priceMin"]);
            int priceMax = Convert.ToInt32(Session["priceMax"]);

            Session["pageIndex"] = 1;

            Search(riceID, provinceID, priceMin, priceMax);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enable"></param>
        private void enablePaging(bool enable)
        {
            if (enable == true)
            {
                imgBtnFirst.Visible = true;
                imgBtnPrevious.Visible = true;
                lblCurrentPage.Visible = true;
                lblSeperate.Visible = true;
                lblTotalPage.Visible = true;
                imgBtnNext.Visible = true;
                imgBtnLast.Visible = true;
            }
            else
            {
                imgBtnFirst.Visible = false;
                imgBtnPrevious.Visible = false;
                lblCurrentPage.Visible = false;
                lblSeperate.Visible = false;
                lblTotalPage.Visible = false;
                imgBtnNext.Visible = false;
                imgBtnLast.Visible = false;
            }
        }
    }
}